import json
import sys
from threading import Thread
from ast import literal_eval

from bot_biggest import Bot_Biggest
from bot_lowest import Bot_Lowest
from bot_random import Bot_Random


def bot_factory(bot_name, init_start=False):
	if bot_name == "lowest":
		return Bot_Lowest(initiate_start=init_start)
	elif bot_name == "random":
		return Bot_Random(initiate_start=init_start)
	elif bot_name == "biggest":
		return Bot_Biggest(initiate_start=init_start)


def run_bot(bot_name, init_start):
	bot = bot_factory(bot_name, init_start)
	try:
		bot.set_name(bot_name)
		bot.connect()
		while True:
			bot.play()
	except KeyboardInterrupt:
		print('interrupt - exiting')
		# TODO: close
		exit(9)


if __name__ == '__main__':
	s = literal_eval(sys.argv[1])
	bots=[]
	for k,v in s.items():
		bots.append([k]*v)
	bots=sum(bots,[])
	for i, bot_name in enumerate(bots):
		Thread(target=run_bot, args=(bot_name, i == len(bots) - 1)).start()
